package com.fcy.teamwork.business.self

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.cardview.widget.CardView
import androidx.lifecycle.lifecycleScope
import com.fcy.teamwork.App
import com.fcy.teamwork.base.BaseActivity
import com.fcy.teamwork.base.fromJson
import com.fcy.teamwork.base.generateColor
import com.fcy.teamwork.base.toJson
import com.fcy.teamwork.business.chat.ChatAct
import com.fcy.teamwork.business.main.homepage.TaskInfoFrag
import com.fcy.teamwork.databinding.ActivitySelfInfoBinding
import com.fcy.teamwork.databinding.ItemTaskBriefBinding
import com.fcy.teamwork.pojo.*
import kotlinx.coroutines.launch

class SelfInfoAct : BaseActivity<ActivitySelfInfoBinding>() {
    private val selfInfoVM: SelfInfoVM by viewModels()
    private lateinit var person: Person
    override fun initBinding(): ActivitySelfInfoBinding =
        ActivitySelfInfoBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        processArgs()
        initListeners()
        binding.actionBar.ibBack.setOnClickListener {
            finish()
        }
    }

    private fun initListeners() {
        binding.rbAddSkill.setOnClickListener {
            supportFragmentManager.beginTransaction().add(AddSkillBottomSheetFrag().apply {
                listener = { skill ->
                    initSkillLabels(listOf(skill))
                }
            }, "").commitNow()
        }
        binding.btnSenMsg.setOnClickListener {
            startActivity(Intent(this, ChatAct::class.java).apply {
                putExtra("targetType", "single")
                putExtra("targetId", person.personId)
            })
        }
    }

    private fun processArgs() {
        val userName = intent.getStringExtra("userName")
        if (userName.isNullOrBlank()) {
            throw IllegalArgumentException("没有解析到正确的用户名")
        }
        selfInfoVM.initUserName(userName)
        val userInfo = intent.getStringExtra("userInfo")
        if (!userInfo.isNullOrBlank()) {
            val person: Person = userInfo.fromJson()
            initPerson(person)
        } else initPerson(null)
    }

    private fun initPerson(p: Person?) {
        lifecycleScope.launch {
            val person = p ?: selfInfoVM.loadMineInfo()
            if (person.personId == App.person.personId) {
                binding.rbAddSkill.visibility = View.VISIBLE
            }
            this@SelfInfoAct.person = person
            binding.actionBar.tvTitle.visibility = View.INVISIBLE
            binding.tvNikeName.text = person.nikeName
            binding.tvDesc.text =
                person.faculty.plus("-").plus(person.major).plus("-").plus(person.clazz)
            initSkillLabels(person.skills.split(","))
            initProjectItems(selfInfoVM.loadRelativeProject())
            if (!intent.getBooleanExtra(
                    "canSenMsg",
                    false
                ) || person.personId == App.person.personId
            ) {
                binding.cvBtnWrap.visibility = View.INVISIBLE
            }
        }
    }

    private fun createLabel(skill: String): CardView {
        val res = CardView(this)
        res.radius = 5F
        val textView = TextView(this).apply {
            setTextColor(Color.BLACK)
            setBackgroundColor(generateColor())
            alpha = 0.6F
            gravity = Gravity.CENTER
            setPadding(10, 0, 10, 0)
            textSize = 18F
            text = skill
        }
        res.addView(textView)
        return res
    }

    private fun initSkillLabels(skills: List<String>) {
        val layout = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply {
            marginEnd = 20
            bottomMargin = 20
        }
        skills.forEach {
            val label = createLabel(it)
            binding.fvSkills.addView(label, layout)
        }
    }

    private fun initProjectItems(projects: List<JobApplyDetail>) {
        val proLayout = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply {
            marginEnd = 20
            bottomMargin = 20
        }
        projects.forEach {
            val label = createProjectItem(it)
            binding.fvPros.addView(label, proLayout)
        }
    }

    private fun createProjectItem(job: JobApplyDetail): CardView {
        val taskBriefBinding = ItemTaskBriefBinding.inflate(layoutInflater)
        taskBriefBinding.llAll.setBackgroundColor(generateColor())
        taskBriefBinding.root.radius = 10F
        taskBriefBinding.root.alpha = 0.8F
        taskBriefBinding.tvTaskInfo.setOnClickListener {
            supportFragmentManager.apply {
                beginTransaction().add(
                    TaskInfoFrag::class.java,
                    Bundle().apply {
                        putBoolean("canApply", false)
                        putString("jobDetail", job.toJson())
                    },
                    "TaskInfoFrag"
                )
                    .commitNow()
            }
        }
        taskBriefBinding.apply {
            tvJobName.text = job.projectHint
            llA.visibility = View.GONE
            llB.visibility = View.GONE
            tvExt.visibility = View.VISIBLE
            tvExt.text = job.ext
//            tvTitle.text = job.owner.nikeName
//            tvFaculty.text = job.owner.faculty
//            tvTaskName.text = job.projectInfo.name
//            tvJobType.text = job.projectInfo.type
        }
        return taskBriefBinding.root
    }

}